package Arrays;

import java.util.Scanner;

/**
 * 作者:hfj
 * 功能:1047. 删除字符串中的所有相邻重复项
 * 日期: 2024/6/29 17:23
 */
public class RemoveDuplicates {
    public static void main(String[] args) {
        System.out.print("请输入一个字符串:");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        System.out.println("去掉相邻重复项后为:" + removeDuplicates(s));
    }

    public static String removeDuplicates(String s) {
        //类似于栈
        StringBuilder result = new StringBuilder();

        //循环遍历s字符串 相同删除 不相同追加进去并且一直判断
        for (char c : s.toCharArray()){
            if (result.length() != 0 && result.charAt(result.length() -1) == c){
                result.deleteCharAt(result.length() -1);
            }else {
                result.append(c);
            }
        }
        return result.toString();
    }
}
